#! /bin/bash

# (c) Michael Goetze, 2010-2011, mgoetze@mgoetze.net
# (c) Thomas Lange, 2011, Uni Koeln

error=0; trap 'error=$(($?>$error?$?:$error))' ERR # save maximum error code

#polkit can not work with hidepid=2
if ifclass -o XORG GNOME GNOME_FC27 XFCE_FC27 KDE_FC27 DDE ; then 
   ainsl /etc/fstab 'proc    /proc    proc    defaults     0     0'
else
   ainsl /etc/fstab 'proc    /proc    proc    defaults,hidepid=2     0     0'
fi

ainsl -v /etc/fstab "sysfs	/sys	sysfs	auto		0 0"

version=`$ROOTCMD rpm -qv kernel | cut -d- -f2-`

use_mkinitrd() {

    # CentOS 5 uses mkinitrd
    $ROOTCMD kudzu -q -k $version
    # Unfortunately mkinitrd is horrible at guessing which modules to include,
    # especially when the running kernel is different than the kernel for which
    # we are creating an initrd...

    drivers=""
    for bus in pci virtio; do
	for dr in `$ROOTCMD kudzu -p -k $version -b $bus|grep driver:|cut -d' ' -f2|sort -u`; do
	    found=`find $target/lib/modules/$version/ -name $dr.ko 2>/dev/null`
	    if [ -n "$found" ]; then
		# add driver only if it's available as .ko module in the destination kernel
		drivers+=" --with=$dr"
	    fi
	done
    done

    $ROOTCMD mkinitrd -f -v $drivers /boot/initrd-$version.img $version

    if [ $? -eq 1 ]; then
	echo "WARNING: generating initrd with list of drivers failed. Trying without."
	$ROOTCMD mkinitrd -f -v /boot/initrd-$version.img $version
    fi
}

# CentOS 5 uses mkinitrd
if [ -f $target/sbin/mkinitrd ]; then
    use_mkinitrd
fi

if [ -f $target/etc/lvm/lvm.conf ]; then
     sed -i -e 's/use_lvmetad = 1/use_lvmetad = 0/' $target/etc/lvm/lvm.conf
     ainsl -av /etc/dracut.conf.d/fai.conf 'add_dracutmodules+=" lvm "'
fi

# call dracut for CentOS 7
if [ -f $target/usr/sbin/dracut ]; then
    # add filesystem driver into initrd
    ainsl -av /etc/dracut.conf.d/fai.conf 'filesystems+="ext4"'
    $ROOTCMD dracut -v --kver $version --force
fi

# call dracut for CentOS 6
if [ -f $target/sbin/dracut ]; then
    # add filesystem driver into initrd
    ainsl -av /etc/dracut.conf.d/fai.conf 'filesystems+="ext4"'
    $ROOTCMD dracut -v $version
fi

exit $error
